<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>               
               <el-row :gutter="20">
                    <el-col :span=7><el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getuserlist">
                         <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
                         </el-input>
                    </el-col>
                    <el-col :span=4><el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
                    </el-col>
               </el-row>
               <el-table :data="userlist" border stripe  >
                    <el-table-column label="#"    type="index"></el-table-column>
                    <el-table-column label="姓名" prop="username"></el-table-column>
                    <el-table-column label="邮箱" prop="email"></el-table-column>
                    <el-table-column label="电话" prop="mobile"></el-table-column>
                    <el-table-column label="角色" prop="role_name"></el-table-column>
                    <el-table-column label="状态" >
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.mg_state" @change="userstatechange(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" >
                        <template slot-scope="scope"> 
                            
                            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditdiaglog(scope.row.id)"></el-button>
                            </el-tooltip>
                            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="remoeuserbyid(scope.row.id)"></el-button>
                            </el-tooltip>
                            <el-tooltip effect="dark" content="修改角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="roleedit(scope.row)"></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
               </el-table>
               <el-pagination
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
                 :current-page="queryinfo.pagenum"
                :page-sizes="[1, 2, 3, 4]"
                :page-size="queryinfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
        </el-card>
        <el-dialog
            title="添加用户"
            :visible.sync="adddialogVisible"
            width="50%"
            @close="adddialogclose">
                <el-form :model="addfrom" :rules="addfromrules" ref="addfromref" label-width="70px">
                    <el-form-item label="用户名" prop="username">
                    <el-input v-model="addfrom.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" >
                    <el-input v-model="addfrom.password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addfrom.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addfrom.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="adddialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="adduser">确 定</el-button>
                </span>
        </el-dialog>
        <el-dialog
            title="修改用户"
            :visible.sync="editdialogvisible"
            width="50%"
            @close="editdialogclose">
            <el-form :model="editfrom" :rules="editfromrules" ref="editfromref" label-width="70px" >
                <el-form-item label="用户名" >
                    <el-input v-model="editfrom.username" disabled></el-input>
                 </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editfrom.email" ></el-input>
                 </el-form-item>
                  <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editfrom.mobile" ></el-input>
                 </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogvisible = false">取 消</el-button>
                <el-button type="primary" @click="edituserinfo">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="分配角色"
            :visible.sync="setRolesdialogVisible"
             width="50%"
             @close="setroledailogcolsed"
            >
            <div>
                <P>当前用户：{{usermes.username}}</P>
                <P>当前角色：{{usermes.role_name}}</P>
                <p>分配新角色：
                      <el-select v-model="selectedrole" placeholder="请选择">
                        <el-option
                         v-for="item in rolelist"
                         :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                     </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRolesdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveroleinfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    created() {
        this.getuserlist()
    },
    data() {
        var checkemail= (rule,value,callback)=>{
            const regemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regemail.test(value)){
                return callback()
            }
            callback(new Error("请正确输入合法邮箱"))
        }
        var checkemobile = (rule,value,callback)=>{
            const regmobile =/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
            if(regmobile.test(value)){
                return callback()
            }
            callback(new Error("请正确输入合法手机号"))
        }
        var editmail= (rule,value,callback)=>{
            const regemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regemail.test(value)){
                return callback()
            }
            callback(new Error("请正确输入合法邮箱"))
        }
        var editmobile =  (rule,value,callback)=>{
            const regmobile =/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
            if(regmobile.test(value)){
                return callback()
            }
            callback(new Error("请正确输入合法手机号"))
        }
        return {
            queryinfo:{
                query:'',
                pagenum:1,
                pagesize:2
            },
            editfrom:{},
            userlist:[],
            usermes:{},
            rolelist:[],
            selectedrole:'',
            total:0,
            adddialogVisible:false,
            editdialogvisible:false,
            setRolesdialogVisible:false,
            addfrom:{
                username:'',
                password:"",
                email:"",
                mobile:""
            },
            addfromrules:{
                username:[
                          { required: true, message: '请输入用户名', trigger: 'blur' },
                          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                          ],
                password:[{ required: true, message: '请输入密码', trigger: 'blur' },
                          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                          ],
                email   :[{ required: true, message: '请输入邮箱', trigger: 'blur' },
                          {
                            validator:checkemail,trigger:'blur'
                          }
                          ],
                mobile   :[{ required: true, message: '请输入正确手机号', trigger: 'blur' },
                          {
                            validator:checkemobile,trigger:'blur'
                          }
                          ]
            } ,
            editfromrules:{
                 email   :[{ required: true, message: '请输入邮箱', trigger: 'blur' },
                          {
                            validator:editmail,trigger:'blur'
                          }
                          ],
                 mobile   :[{ required: true, message: '请输入手机号', trigger: 'blur' },
                          {
                            validator:editmobile,trigger:'blur'
                          }]
            }
        }
    },
    methods: {
      async getuserlist(){
         const {data:res} = await this.$http.get('users',{params:this.queryinfo})
         if(res.meta.status!=200) return this.$message.error("获取用户列表失败")
         
         this.userlist = res.data.users
         this.total = res.data.total
        
         
          } ,
        handleSizeChange(newpagesize){
            
            this.queryinfo.pagesize = newpagesize
            this.getuserlist()
        } ,
        handleCurrentChange(newpage){
            this.queryinfo.pagenum = newpage
            this.getuserlist()
        } ,
       async userstatechange(userinfo){
            const {data:res}  = await  this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status!=200) {
                userinfo.mg_state = !userinfo.mg_state
                return this.$message.error("更新用户状态失败")
            }
            this.$message.success("更新用户状态成功")  
        } ,
        adddialogclose(){
            this.$refs.addfromref.resetFields()
        } ,
        adduser(){
            this.$refs.addfromref.validate(async vaild=>{
                if(!vaild) return
                const {data:res} = await this.$http.post('users',this.addfrom)
                if(res.meta.status!=201) return this.$message.error("添加用户失败")
                this.$message.success("添加用户成功")
                this.adddialogVisible = false
                this.getuserlist()
            })
        },
         async showeditdiaglog(id){
              
              this.editdialogvisible=true
              const {data:res} = await this.$http.get(`users/${id}`)
              if(res.meta.status!=200) return this.$message.error("查询用户信息失败")
              this.editfrom = res.data
              
          } ,
          editdialogclose(){
              this.$refs.editfromref.resetFields()
          },
          edituserinfo(){
              this.$refs.editfromref.validate(async vaild=>{
                  if(!vaild) return 
                  const {data:res} = await this.$http.put('users/'+this.editfrom.id,{
                      email:this.editfrom.email,
                      mobile:this.editfrom.mobile,
                      
                  }) 
                  if(res.meta.status!=200) return this.$message.error("更新用户信息失败")   
                  this.editdialogvisible =false
                  this.getuserlist()
                  this.$message.success("成功更新用户信息")
                    
              })
          },
         async remoeuserbyid(id){
            const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
        }).catch(err=>{
            return err
        })
        if(res!='confirm') {
            return this.$message.info("已取消当前删除操作")
        }
        const {data:ruesult} = await this.$http.delete("users/"+id)
        if(ruesult.meta.status!=200) return this.$message.error("删除用户失败")
        this.$message.success("成功删除当前用户")
        this.getuserlist()    
          },
        async roleedit(usermes){
              this.usermes = usermes
              const {data:res} =  await this.$http.get('roles')
              if(res.meta.status!=200) return this.$message.error("获取数据失败")
              this.rolelist = res.data
              this.setRolesdialogVisible =true
          } ,
         async saveroleinfo(){
              if(!this.selectedrole) 
              return  this.$message.error("请选择要分配的角色")
              const {data:res} = await this.$http.put(`users/${this.usermes.id}/role`,{
                  rid:this.selectedrole
              })
              if(res.meta.status!=200) return this.$message.error("修改用户角色失败")
              this.$message.success("修改用户角色成功")
              this.setRolesdialogVisible = false
              this.getuserlist()
          },
          setroledailogcolsed(){
              this.selectedrole='',
              this.usermes ={}
          }
    },
}
</script>

<style scoped>

</style>